<?php
/**
 * 后台Index相关
 */
namespace Home\Controller;
use Think\Controller;
use Think\Exception;

class AdminController extends CommonController {

	public function index() {
		$admins = D('Admin')->getAdmins();
		$this->assign('admins', $admins);
		$this->display();
	}

	public function add() {
		$rules = array(
			array('username', 'require', '用户名不能为空哦〒_〒！'),
			array('username', '', '用户名已存在', 0, 'unique', 3),
			array('password', 'require', '密码不能为空〒_〒！'),
		);
		$admin = M("Admin");
		// 保存数据
		if (IS_POST) {
			if (!$admin->validate($rules)->create()) {
				return show(0, $admin->getError());
			} else {
				$_POST['password'] = getMd5Password($_POST['password']);
				// 新增
				$id = D("Admin")->insert($_POST);
				if (!$id) {
					return show(0, '新增失败');
				} else {return show(1, '新增成功');}
			}
		}
		$this->display();
	}

	public function setStatus() {
		$data = array(
			'admin_id' => intval($_POST['id']),
			'status' => intval($_POST['status']),
		);
		return parent::setStatus($_POST, 'Admin');
	}

	public function personal() {
		$res = $this->getLoginUser();
		$user = D("Admin")->getAdminByAdminId($res['admin_id']);
		$this->assign('vo', $user);
		$this->display();
	}

	public function save() {
		$user = $this->getLoginUser();
		if (!$user) {
			return show(0, '用户不存在');
		}

		$data['realname'] = $_POST['realname'];
		$data['email'] = $_POST['email'];

		try {
			$id = D("Admin")->updateByAdminId($user['admin_id'], $data);
			if ($id === false) {
				return show(0, '配置失败');
			}
			return show(1, '配置成功');
		} catch (Exception $e) {
			return show(0, $e->getMessage());
		}
	}

}